import React, { useContext, useState } from "react";
import { connect } from "react-redux";
import { ThemeProvider } from "@material-ui/core";

import Context from "../../Context.js";
import { setAccount, setServer } from "../../store/actions/account";

import { useStyles } from "./Account.jss";

function Account(props) {
  const { theme } = useContext(Context);
  const classes = useStyles(theme);
  const [userName, setUsername] = useState(getUserName());
  const [serverAddress, setServerAddress] = useState(getServerAddress());
  return (
    <ThemeProvider theme={theme}>
      <div className={classes.root}>
        <div className={classes.rows}>
          <div className={classes.row}>
            <div className={classes.title}>Username:</div>
            <div className={classes.inputBox}>
              <input
                className={classes.input}
                value={userName}
                maxLength="16"
                onChange={(e) => {
                  setUsername(e.target.value);
                }}
              />
            </div>
          </div>
          <div className={classes.row}>
            <div className={classes.title}>Server address:</div>
            <div className={classes.inputBox}>
              <input
                className={classes.input}
                value={serverAddress}
                // maxLength="21"
                onChange={(e) => {
                  setServerAddress(e.target.value);
                }}
              />
            </div>
          </div>
        </div>
        <div>
          <div className={classes.saveForm}>
            <div className={classes.saveFormElement}>
              <div className={classes.saveButton} onClick={save}>
                save
              </div>
            </div>
            <div className={classes.saveFormElement}>
              <div className={classes.cancelButton} onClick={cancel}>
                cancel
              </div>
            </div>
          </div>
        </div>
      </div>
    </ThemeProvider>
  );

  function save(e) {
    props.setAccount(userName);
    props.setServer(serverAddress);
  }

  function cancel(e) {
    setUsername(getUserName());
    setServerAddress(getServerAddress());
  }

  function getUserName() {
    try {
      return props.account.userName;
    } catch (err) {
      return "";
    }
  }

  function getServerAddress() {
    try {
      return props.server.serverAddress;
    } catch (err) {
      return "";
    }
  }
}

const mapStateToProps = (state) => {
  return {
    account: state.account.account,
    server: state.account.server,
  };
};

const mapDispathToProps = {
  setAccount,
  setServer,
};

export default connect(mapStateToProps, mapDispathToProps)(Account);
